/**
 * 
 */
package com.glodon.paas.account.dao.redis;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

import com.glodon.paas.account.dao.TokenDao;
import com.glodon.paas.account.dao.domain.OAuthTokenEntity;

/**
 * @author hankl
 * @date  2012-11-2
 */
public class TokenDaoRedisImpl implements TokenDao {

	@Autowired
	private JedisPool pool;
	
	@Autowired
	 private OAuthTokenDaoRedisImpl redisTokenDao; 
	
	public TokenDaoRedisImpl(OAuthTokenDaoRedisImpl redisTokenDao,JedisPool pool){
		this.redisTokenDao  = redisTokenDao;
		this.pool  = pool;
	}
	
	/* (non-Javadoc)
	 * @see com.glodon.paas.account.dao.TokenDao#getAccessTokens(java.lang.String)
	 */
	@Override
	public List<OAuthTokenEntity> getAccessTokens(String userId) {
		final Jedis jedis = pool.getResource();
		List<OAuthTokenEntity> tokenList = new ArrayList<OAuthTokenEntity>();
		String uidKey = OAuthTokenDaoRedisImpl.USERID_PREFIX+userId;
		try{
			Set<String> tokenSet = jedis.smembers(uidKey);			
			for(String tokenKey: tokenSet)
			{
				OAuthTokenEntity entity = redisTokenDao.readToken(tokenKey);
				tokenList.add(entity);			
			}	
			
		}finally{
			pool.returnResource(jedis);
		}	
		return tokenList;
	}
	
	/* (non-Javadoc)
	 * @see com.glodon.paas.account.dao.DBDao#insert(java.lang.Object)
	 */
	@Override
	public String insert(OAuthTokenEntity entity) {
		return redisTokenDao.insert(entity);		
	}

	/* (non-Javadoc)
	 * @see com.glodon.paas.account.dao.DBDao#get(java.lang.Object)
	 */
	@Override
	public OAuthTokenEntity get(String id) {
		return redisTokenDao.readToken(id);
	}

	/* (non-Javadoc)
	 * @see com.glodon.paas.account.dao.DBDao#delete(java.lang.Object)
	 */
	@Override
	public int delete(String id) {
		return redisTokenDao.delete(id);		
	}

}
